import {
  getUserInfo,
  updateUserInfo,
  addUserInfo,
  uploadFile
} from '../../../services/user/index';
import {
  baseUrl
} from '../../../utils/request'
import {
  phoneEncryption
} from '../../../utils/util';
import Toast from 'tdesign-miniprogram/toast';
import cityList from '../../../utils/city';
import province from '../../../utils/province'
import ActionSheet, {
  ActionSheetTheme
} from 'tdesign-miniprogram/action-sheet/index';
const year = new Date().getFullYear()
let timeItems = []
let classItems = []
let startY = 1920;
while(startY <= year) {
  timeItems.push({
    label: startY
  })
  startY ++
}
for (let i = 0; i < 30; i++) {
  classItems.push({
    label: `高三${i+1}班`,
    value: i + 1
  })
}
const areaList = province.map(item => {
  const cli = cityList[item.value]
  return {
    value: item.value,
    label: item.label,
    children: cli
  }
})
const rules = {
  avatar: '头像不能为空',
  nickName: '用户昵称不能为空',
  userName: '姓名不能为空',
  sex: '性别不能为空',
  userType: '角色不能为空',
  phone: '联系方式不能为空',
  company: '公司不能为空',
  city: '所在城市不能为空',
  province: '所在省份不能为空',
  grade: '届别不能为空',
  classOf: '班级不能为空',
  postName: '教职工岗位不能为空',
}
Page({
  data: {
    personInfo: {
      avatar: '',
      nickName: '',
      userName: '',
      sex: 0,
      userType: '',
      birthday: '',
      city: '',
      province: '',
      grade: '',
      classOf: '',
      phone: '',
      company: '',
      postName: '',
      openId: wx.getStorageSync('openid')
    },
    typeVisible: false,
    openId: '',
    dateVisible: false,
    areavisible: false,
    areaList,
    phoneError: false,
    hasRegister: false,

  },
  onLoad(query) {
    const {
      openId
    } = query
    if (!openId) return
    this.fetchData(openId);
  },
  fetchData(openId) {
    if (!openId) return;
    this.setData({
      openId
    })
    wx.showLoading()
    getUserInfo(openId).then(res => {
      if (res.data.code == 200 && res.data.data) {
        const data = res.data.data;
        this.setData({
          personInfo: data,
          hasRegister: true,
          openId
        })
        wx.hideLoading()
      } else {
        wx.getSetting({
          success: (res) => {
            if (res.authSetting['scope.userInfo']) {
              wx.getUserInfo().then(res => {
                if (res.errMsg == 'getUserInfo:ok') {
                  this.setData({
                    personInfo: {
                      ...this.data.personInfo,
                      avatar: res.userInfo.avatarUrl,
                      nickName: res.userInfo.nickName,
                      city: res.userInfo.city,
                      province: res.userInfo.province,
                      sex: res.userInfo.gender,
                      openId: openId
                    }
                  })
                }
                wx.hideLoading()
              })
            }
          }
        })
      }
    })
  },
  changeInfo(e) {
    const {
      value
    } = e.detail
    const {
      type
    } = e.target.dataset
    const personInfo = this.data.personInfo;
    personInfo[type] = value
    this.setData({
      personInfo
    })
  },
  onClickCell({
    currentTarget
  }) {
    const {
      dataset
    } = currentTarget;
    switch (dataset.type) {
      case 'avatarUrl':
        this.toModifyAvatar();
        break;
      case 'grade':
        this.bindActionSheet();
        break;
      case 'city':
        this.setData({
          areavisible: true
        })
        break;
      case 'classOf':
        this.classOfHander()
        break;
      default: {
        break;
      }
    }
  },
  updateUserInfo() {
    const {
      personInfo,
      hasRegister
    } = this.data
    wx.showLoading();
    if (hasRegister) {
      updateUserInfo(personInfo).then(res => {
        wx.hideLoading();
        if (res.data.code == 200) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '更新成功',
            theme: 'success',
          });
          wx.setStorageSync('openid', this.data.openId)
          wx.navigateBack();
        }
      })
    } else {
      addUserInfo({
        ...personInfo
      }).then(res => {
        wx.hideLoading();
        if (res.data.code == 200) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '注册成功',
            theme: 'success',
          });
          wx.setStorageSync('openid', this.data.openId)
          wx.navigateBack();
        }
      })
    }

  },
  onClose() {
    this.setData({
      typeVisible: false,
    });
  },
  onConfirm(e) {
    const {
      value
    } = e.detail;
    this.setData({
        typeVisible: false,
        'personInfo.gender': value,
      },
      () => {
        const {
          personInfo,
          openId
        } = this.data;
        updateUserInfo({
          openId: openId,
          ...personInfo,
          phonen: personInfo.phoneNumber
        }).then(res => {
          if (res.data.code == 200) {
            Toast({
              context: this,
              selector: '#t-toast',
              message: '设置成功',
              theme: 'success',
            });
          }
        })
        console.log(this.data.personInfo)

      },
    );
  },
  async toModifyAvatar() {
    // try {
    const tempFilePath = await new Promise((resolve, reject) => {
      wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          let types = res.tempFiles[0].path.substring(res.tempFiles[0].path.length - 3);
          console.log(types)
          console.log(res)
          if (types !== 'jpg' && types !== 'png') {
            Toast({
              context: this,
              selector: '#t-toast',
              message: `头像只支持jpg/png格式`,
              theme: 'error',
            });
            return;
          }
          const {
            path,
            size
          } = res.tempFiles[0];
          if (size <= 10485760) {
            resolve(path);
          } else {
            reject({
              errMsg: '图片大小超出限制，请重新上传'
            });
          }
        },
        fail: (err) => reject(err),
      });
    });
    uploadFile(tempFilePath).then(res => {
      if (res.errMsg == 'uploadFile:ok') {
        const data = JSON.parse(res.data)
        this.setData({
          personInfo: {
            ...this.data.personInfo,
            avatar: baseUrl + '/' + data.fileName
          }
        })
        Toast({
          context: this,
          selector: '#t-toast',
          message: `更新头像成功`,
          theme: 'success',
        });
      }
    })


    // } catch (error) {
    //   if (error.errMsg === 'chooseImage:fail cancel') return;
    //   Toast({
    //     context: this,
    //     selector: '#t-toast',
    //     message: error.errMsg || error.msg || '修改头像出错了',
    //     theme: 'error',
    //   });
    // }
  },
  bindActionSheet() {
    ActionSheet.show({
      theme: ActionSheetTheme.List,
      selector: '#t-action-sheet',
      context: this,
      items: timeItems,
    });
  },
  classOfHander() {
    ActionSheet.show({
      theme: ActionSheetTheme.List,
      selector: '#t-time-sheet',
      context: this,
      items: classItems,
    });
  },
  timeSelected(e) {
    const {
      selected
    } = e.detail
    this.setData({
      personInfo: {
        ...this.data.personInfo,
        classOf: selected.value
      }
    })
  },
  handleSelected(e) {
    console.log(e.detail);
    const {
      selected
    } = e.detail
    this.setData({
      personInfo: {
        ...this.data.personInfo,
        grade: selected.label
      }
    })
  },
  openTime() {
    this.setData({
      dateVisible: true
    })
  },
  onConfirm(e) {
    const {
      value
    } = e.detail
    this.setData({
      personInfo: {
        ...this.data.personInfo,
        birthday: value
      }
    })

  },
  onColumnChange() {},
  hidePicker() {
    this.setData({
      dateVisible: false
    })
  },
  areaChange(e) {
    const {
      selectedOptions
    } = e.detail;
    if (selectedOptions.length > 1) {
      this.setData({
        personInfo: {
          ...this.data.personInfo,
          province: selectedOptions[1].province,
          city: selectedOptions[1].label
        }
      })
    }
  },
  areaPick(e) {
    console.log(e, 'pick')
  },
  onPhoneInput(e) {
    const {
      phoneError
    } = this.data;
    const isPhoneNumber = /^[1][3,4,5,7,8,9][0-9]{9}$/.test(e.detail.value);
    if (phoneError === isPhoneNumber) {
      this.setData({
        phoneError: !isPhoneNumber,
      });
    } else {
      const personInfo = this.data.personInfo;
      personInfo['phone'] = e.detail.value
      this.setData({
        personInfo
      })
    }
  },
  suggest() {
    const personInfo = this.data.personInfo
    let msg = '';
    Object.keys(personInfo).every(key => {
      if (!personInfo[key]) {
        if (key == 'company' && personInfo.userType != '00') {
          return true;
        }  else if (key == 'grade' && personInfo.userType != '00') {
          return true;
        }  else if (key == 'classOf' && personInfo.userType != '00') {
          return true;
        }  else if (key == 'postName' && personInfo.userType != '01') {
          return true;
        }else {
          msg = rules[key]
          return false;
        }
      }
      return true;
    })
    if (msg) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: msg,
        theme: 'error',
      });
    } else {
      this.updateUserInfo()
    }
  }
});